package com.pan.server.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pan.common.constant.MessageConstant;
import com.pan.common.constant.PermissionIdConstant;
import com.pan.common.exception.AccountAlreadyExistException;
import com.pan.common.exception.AccountLockedException;
import com.pan.common.exception.AccountNotFoundException;
import com.pan.common.exception.PasswordErrorException;
import com.pan.pojo.dto.UserDTO;
import com.pan.pojo.dto.UserLoginDTO;
import com.pan.pojo.entity.User;
import com.pan.pojo.vo.UserAdminVO;
import com.pan.server.mapper.OrdersMapper;
import com.pan.server.mapper.UserMapper;
import com.pan.server.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrdersMapper ordersMapper;


    /**
     * 用户登录
     * @param userLoginDTO
     * @return
     */
    public User login(UserLoginDTO userLoginDTO){
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();

        User user = userMapper.selectByUsername(username);

        // TODO: 密码加密
//        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if(user == null){
            throw new AccountNotFoundException(MessageConstant.USER_NOT_FOUND);
        }
        if(!user.getPassword().equals(password)){
            throw new PasswordErrorException(MessageConstant.Password_ERROR);
        }
        if(user.getPermissionId() == PermissionIdConstant.ACCOUNT_LOCKED_PERMISSION_ID){
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        return user;
    }

    /**
     * 用户注册
     * @param userDTO
     * @return
     */
    public User register(UserDTO userDTO) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();

        User user = userMapper.selectByUsername(username);

        if(user != null){
            throw new AccountAlreadyExistException(MessageConstant.ACCOUNT_ALREADY_EXIST);
        }

        // TODO 密码加密
//        password = DigestUtils.md5DigestAsHex(password.getBytes());


        User resgisterUser = User.builder()
                .username(username)
                .password(password)
                .name(userDTO.getName())
                .gender(userDTO.getGender())
                .location(userDTO.getLocation())
                .permissionId(PermissionIdConstant.USER_PERMISSION_ID)
                .build();

        userMapper.insert(resgisterUser);

        return resgisterUser;
    }

    /**
     * 更新用户信息
     * @param userDTO
     * @return
     */
    public User updateUser(UserDTO userDTO) {

        String username = userDTO.getUsername();

        //TODO 密码加密
        String password = userDTO.getPassword();
//        password = DigestUtils.md5DigestAsHex(userDTO.getPassword().getBytes());
//        userDTO.setPassword(password);

        userMapper.updateUser(userDTO);

        return userMapper.selectByUsername(username);
    }

    @Override
    public PageInfo<UserAdminVO> getAllUsers(Integer pageNum, Integer pageSize) {

        PageHelper.startPage(pageNum, pageSize);

        List<UserAdminVO> userAdminVOList = userMapper.getAllUsers();

        PageInfo<UserAdminVO> pageInfo = new PageInfo<>(userAdminVOList);

        return pageInfo;
    }

    @Override
    public void deleteUser(Integer id) {
        // TODO 外键
        List<Integer> orderId = ordersMapper.queryOrdersByUserId(id);

        for (Integer integer : orderId) {
            ordersMapper.deleteOrderDetail(integer);
        }
//        ordersMapper.deleteOrderDetail(orderId);
        ordersMapper.deleteOrderByUserId(id);

        userMapper.deleteUser(id);
    }

    /**
     * 更新用户权限
     * @param userId
     * @param permissionId
     */
    @Override
    public void updateUserAdmin(Integer userId, Integer permissionId) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("permissionId", permissionId);
        userMapper.updateUserAdmin(map);
    }
}